package com.ruike.alisurface.ui.payPage;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TextView;

import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.CardCreateOrderByProductBean;
import com.ruike.alisurface.bean.CardCreateOrderBySlotBean;
import com.ruike.alisurface.bean.CardOrderBean;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.CardHttp;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class PayCardActivity extends BaseAty {

    @BindView(R.id.payCard_operationTips_tv)
    TextView operationTipsTv;
    @BindView(R.id.payCard_payInfo_tabLayout)
    TableLayout payInfoTabLayout;
    @BindView(R.id.payCard_cardNumber_tv)
    TextView cardNumberTv;
    @BindView(R.id.payCard_payPrice_tv)
    TextView payPriceTv;
    @BindView(R.id.payCard_yemoney_tv)
    TextView yeMoneyTv;
    @BindView(R.id.payCard_payTime_tv)
    TextView payTimeTv;
    @BindView(R.id.payCard_countTime_tv)
    TextView countTimeTv;
    @BindView(R.id.payCard_inputCard_et)
    EditText inputCardEt;

    List<CarGoodsBeans> payCarList; // 商品 数据
    double money = 0.0f;
    ShopDetailBean shopDetailBean;
    String orderId; // 创建的订单ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pay_card;
    }

    @Override
    protected void initViews() {
        startCountdownTimer(120, countTimeTv, null);
        initTitleBar(false);
    }

    @Override
    protected void initData() {

        inputCardEt.addTextChangedListener(textWatcher);
        inputCardEt.clearFocus();
        inputCardEt.setEnabled(false);

        // 计算购物车商品的总金额并展示在界面上
        payCarList = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        if (payCarList == null || payCarList.size() <= 0) {
            return;
        }
        for (CarGoodsBeans carGoodsBean : payCarList) {
            if (carGoodsBean != null && carGoodsBean.getPrice() > 0) {
                money += carGoodsBean.getPrice();
            }
        }
        payPriceTv.setText(new StringBuffer("¥").append(money));

        operationTipsTv.setText("正在创建订单...");
        if (ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 1) == 1) {
            L.i("按货道展示下单");
            CardHttp.createOrderBySlot(payCarList, this);
        } else {
            L.i("按商品类型展示下单");
            CardHttp.createOrderByProduct(payCarList, this);
        }

    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.length() >= 10) {
                inputCardEt.clearFocus();
                inputCardEt.setEnabled(false);
                showProgressDialog("正在上传卡号...");
                String numberStr = editable.toString().trim();
                CardHttp.cardPay(orderId, numberStr, "", PayCardActivity.this);
            }
        }
    };

    @OnClick({R.id.payCard_goback_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.payCard_goback_imgv:
                startCountdownTimer(0, null, null);
                break;
        }
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        // 串口发送的EventBus消息接收
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (CardHttp.CREATE_ORDER_BY_PRODUCT.equals(requestUrl) || CardHttp.CREATE_ORDER_BY_SLOT.equals(requestUrl)) { // 创建订单返回数据

            CardOrderBean cardOrderBean = GsonUtils.json2Model(requestJsonStr, CardOrderBean.class);
            CardOrderBean.DataBean data = cardOrderBean.getData();
            orderId = data.getId();

            shopDetailBean = new ShopDetailBean(orderId);
            shopDetailBean.setPromotion_fee(data.getPromotion_fee());
            shopDetailBean.setTotal_fee(data.getTotal_fee());
            shopDetailBean.setPay_fee(data.getPay_fee());
            money = data.getPay_fee();
            L.i("shopDetailBean", shopDetailBean.toString());
            List<CardOrderBean.DataBean.DetailsBean> resultDetailList = data.getDetails();

            List<ShopDetailBean.OrderDetailsBean> detailsBeanList = new ArrayList<>();
            for (CardOrderBean.DataBean.DetailsBean resultDetailBean : resultDetailList) {
                ShopDetailBean.OrderDetailsBean orderDetailsBean = new ShopDetailBean.OrderDetailsBean();

                orderDetailsBean.setSlotTypeId(resultDetailBean.getSlotTypeId());
                orderDetailsBean.setSlotIndex(resultDetailBean.getSlotIndex());
                orderDetailsBean.setQuantity(resultDetailBean.getQuantity());

                detailsBeanList.add(orderDetailsBean);
            }

            shopDetailBean.setDetailOrderList(detailsBeanList);

            operationTipsTv.setText("请输入卡号或刷卡读取...");
            inputCardEt.setEnabled(true);
            inputCardEt.requestFocus();

        }
        if (CardHttp.CARD_PAY.equals(requestUrl)) { // 上传刷卡订单扣款信息
            String balanceStr = "0.00";
            try {
                JSONObject jsonObject = new JSONObject(requestJsonStr);
                JSONObject dataJson = jsonObject.optJSONObject("data");
                if (dataJson != null) {
                    balanceStr = dataJson.optString("balance");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            showRightTip("当前剩余余额：" + balanceStr);

            Bundle bundle = new Bundle();
            bundle.putString("pay_type", "card");
            bundle.putSerializable("orderBeanData", shopDetailBean);
            startActivity(PayShowShopActivity.class, bundle);
            finish();
        }
    }

    @Override
    public void onError(String requestUrl, String requestMsg) {
        super.onError(requestUrl, requestMsg);
        showErrorTip(requestMsg);
        if (CardHttp.CREATE_ORDER_BY_PRODUCT.equals(requestUrl) || CardHttp.CREATE_ORDER_BY_SLOT.equals(requestUrl)) { // 创建订单返回数据
            startCountdownTimer(3, null, null);
        } else {
            inputCardEt.setEnabled(true);
            inputCardEt.requestFocus();
        }
    }

}